﻿
using Company.Core.Logger;
using NModbus;


namespace Company.Plc.NModbus
{
    public class NModbusPlc : PlcBase
    {
        private IModbusMaster master;// NModbus的主站对象
        public override bool DoInit()
        {
            try
            {
                tcpClient = new();
                tcpClient.Connect(plcConfig.IP, plcConfig.Port);
                var factory = new ModbusFactory();
                master = factory.CreateMaster(tcpClient);
            }
            catch (Exception ex)
            {

                Logs.Error(ex);
            }

            return master != null;
        }

        public override ushort[] Read(string address, ushort length)
        {
            if (ushort.TryParse(address,out var result))//安全类型转换的 TryParse 方法语法
            {
#if DEBUG
                var array = new ushort[length];
                Random random = new();
                for (int i = 0; i < length; i++)
                {
                    array[i] = (ushort)random.Next(111, 999);
                    Thread.Sleep(10);
                }
                return array;
#else
                return master.ReadHoldingRegisters(plcConfig.SlaveAddress, result, length);
#endif

            }
            else
            { 
                return new ushort[0];
            }
        }

        public override bool Write(string address, ushort[] values)
        {
            if (ushort.TryParse(address, out var result))//安全类型转换的 TryParse 方法语法
            {
                 master.WriteMultipleRegisters(plcConfig.SlaveAddress, result, values);//写多个寄存器
                return true;
            }
            else
            {
                return false;
            }
        }
        public override bool Write(string address, ushort value)
        {
            if (ushort.TryParse(address, out var result))//安全类型转换的 TryParse 方法语法
            {
                master.WriteSingleRegister(plcConfig.SlaveAddress, result, value);//写单个寄存器
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
